<?php
// +----------------------------------------------------------------------
// | Scallion 
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.scallion.top All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Liuxg < 420695648@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Db;

class TeacherController extends AdminBaseController
{

    /**
     * 教师管理
     */
    public function index()
    {
		// $data = db('teacher')->order('id asc')->paginate(10);
		// $this->assign('page', $data->render());
		// $this->assign("data", $data);
        return $this->fetch();
    }
	
	/**
     * 教师查询
     */
	public function find_teacher(){
		if($this->request->param()){
			$param = $this->request->param();
			if(!isset($param['name'])){
				$param['name'] = '';
			}
			if(!isset($param['phone'])){
				$param['phone'] = '';
			}
			$map['name'] = ['like','%'.$param['name'].'%'];
			$map['phone'] = ['like','%'.$param['phone'].'%'];
			$join = [
				['user w','a.union_id=w.id'],
			];
			$result = db('teacher')->alias('a')->where($map)->order('a.id asc')->join($join)->field('a.id,a.union_id,a.name,a.phone,a.sex,a.IDcard,a.birthday,a.entry_time,w.user_status,w.user_login,w.user_email')->paginate(10);
			$this->assign('page', $result->render());
			$this->assign("teacher_info", $result);
			$this->assign("param", $param);
			// dump(json_encode($result));
			return $this->fetch('index');
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	/**
     * 自动补全
     */
	public function find_teacher_name(){
		$param = $this->request->param();
		$result = db('teacher')->field('name,phone')->where('name','like','%'.$param['name'].'%')->limit('5')->select();
		return json_encode($result);
	}
	
	public function find_teacher_phone(){
		$param = $this->request->param();
		$result = db('teacher')->field('name,phone')->where('phone','like','%'.$param['phone'].'%')->limit('5')->select();
		return json_encode($result);
	}
	
	/**
     * 新增/编辑教师
     */
	public function add_teacher(){
		return $this->fetch();
	}
	
	public function edit_teacher(){
		if($this->request->isGet()){
			$param = $this->request->param();
			$result = db('teacher')->where('id='.$param['id'])->find();
			$result['introduction'] = cmf_replace_content_file_url(htmlspecialchars_decode($result['introduction']));
			$this->assign("param", $result);
			return $this->fetch();
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function add_teacher_Post(){
		if ($this->request->isPost()){
			$param = $this->request->param();
			$result = $this->validate($param, 'teacher');
            if ($result !== true) {
                $this->error($result);
            }
			else
			{
				// dump($param);
				//新增管理员，获取管理员id
				$data['user_type'] = '1';
				$data['sex'] = $param['sex'];
				$data['birthday'] = strtotime($param['birthday']);
				$data['last_login_time'] = time();
				$data['score'] = '1';
				$data['coin'] = '1';
				$data['balance'] = '0';
				$data['create_time'] = time();
				$data['user_status'] = '1';
				$data['user_login'] = $param['phone'];
				$data['user_pass'] = cmf_password('123456');
				$data['user_nickname'] = $param['name'];
				$data['user_email'] = $param['phone'].'@ssycjy.com';
				$data['last_login_ip'] = '0.0.0.0';
				$data['mobile'] = $param['phone'];
				$admin_id = db('user')->insertGetId($data);
				// 设置角色 role_user    默认3为教师
				$role_user_data['role_id'] = '3';
				$role_user_data['user_id'] = $admin_id;
				db('role_user')->insert($role_user_data);
				// 教师数据整理
				$param['union_id'] = $admin_id;
				$param['birthday'] = date("Y-m-d",strtotime($param['birthday']));
				$param['entry_time'] = date("Y-m-d",strtotime($param['entry_time']));
				$param['update_time'] = time();
				if(isset($param['introduction'])){
					$param['introduction'] = htmlspecialchars(cmf_replace_content_file_url(htmlspecialchars_decode($param['introduction']), true));
				}
				$res = db('teacher')->insert($param);
				if($res){
					
					// 填写日志
					$action = '新增教师';
					$temp_param = $param;
					unset($temp_param['introduction']);
					unset($temp_param['note']);
					$json_data = json_encode($temp_param);
					$result = '成功';
					self::data_log($action,$json_data,$result);
					
					$this->success('添加教师成功',url('teacher/find_teacher',['name'=>$param['name'],'phone'=>$param['phone']]));
				}
				else{
					$this->error('系统错误！errcode：-401');
				}
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function edit_teacher_Post(){
		if ($this->request->isPost()){
			$param = $this->request->param();
			
			//教师是否存在
			$is_exist = db('teacher')->where('id='.$param['id'])->find();
			if(!$is_exist){
				$this->error('教师不存在！');
			}
			// 验证基本信息规则
			if($param['phone'] === $is_exist['phone']){
				$result = $this->validate($param, 'teacher.edit');
			}
			else{
				$result = $this->validate($param, 'teacher');
			}
            if ($result !== true) {
                $this->error($result);
            }
			else
			{
				//整理管理员账号数据
				$data['sex'] = $param['sex'];
				$data['birthday'] = strtotime($param['birthday']);
				$data['user_login'] = $param['phone'];
				$data['user_nickname'] = $param['name'];
				$data['user_email'] = $param['phone'].'@ssycjy.com';
				$data['mobile'] = $param['phone'];
				db('user')->where('id='.$is_exist['union_id'])->update($data);
				// 教师数据整理
				$param['birthday'] = date("Y-m-d",strtotime($param['birthday']));
				$param['entry_time'] = date("Y-m-d",strtotime($param['entry_time']));
				$param['update_time'] = time();
				if(isset($param['introduction'])){
					$param['introduction'] = htmlspecialchars(cmf_replace_content_file_url(htmlspecialchars_decode($param['introduction']), true));
				}				
				$res = db('teacher')->where('id='.$param['id'])->update($param);
				if($res){
					
					//填写日志
					$action = '编辑教师';
					$temp_param = $param;
					unset($temp_param['introduction']);
					unset($temp_param['note']);
					$json_data = json_encode($temp_param);
					$result = '成功';
					$temp_param_old_data = $is_exist;
					unset($temp_param_old_data['introduction']);
					$json_old_data = json_encode($temp_param_old_data);
					self::data_log($action,$json_data,$result,$json_old_data);
					
					$this->success('保存教师资料成功',url('teacher/find_teacher',['name'=>$param['name'],'phone'=>$param['phone']]));
				}
				else{
					$this->error('系统错误！errcode：-402');
				}
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function active_teacher(){
		if ($this->request->isPost()){
			$ids = $this->request->param();
			$operate_log = '';
			if(count($ids)<1){
				$this->error('请选择要激活的教师后台账号！');
			}
			else{
				for($i=0;$i<count($ids['ids']);$i++){
					$is_exist_teacher[$i] = db('teacher')->where('id='.$ids['ids'][$i])->find();
					if(!$is_exist_teacher[$i]){
						//反馈
						$operate_log = $operate_log . 'ID：'.$ids['ids'][$i].'的教师不存在！</br>';
					}
					else{
						$is_exist_admin[$i] = db('user')->where('id='.$is_exist_teacher[$i]['union_id'])->find();
						if(!$is_exist_admin[$i]){
							//激活反馈
							$operate_log = $operate_log . 'union_id：'.$is_exist_teacher[$i]['union_id'].'的教师后台账号不存在！</br>';
						}
						else{
							//填写日志
							$action = '激活教师管理员账号'.$is_exist_admin[$i]['user_login'].'union_id为：'.$is_exist_teacher[$i]['union_id'];
							$temp_param = $is_exist_admin[$i];
							unset($temp_param['user_login']);
							unset($temp_param['user_pass']);
							$json_data = json_encode($temp_param);
							$result = '成功';
							$first = self::data_log($action,$json_data,$result);
							if(!$first){$this->error('记录日志错误！ -409');}
							//填写user表user_status为1（激活）
							$second['user_status'] = '1'; 
							$third = db('user')->where('id='.$is_exist_teacher[$i]['union_id'])->update($second);
							//删除反馈
							if($first && $third){
								$operate_log = $operate_log . 'union_id：'.$is_exist_teacher[$i]['union_id'].'的教师后台账号激活成功！</br>';
							}
							else{
								$operate_log = $operate_log . 'union_id：'.$is_exist_teacher[$i]['union_id'].'的教师后台账号已经激活！</br>';
							}
						}
					}
				}
				$this->success($operate_log,url('admin/teacher/find_teacher',array('name'=>$ids['name'],'phone'=>$ids['phone'],'from'=>'ban_teacher')));
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function ban_teacher(){
		if ($this->request->isPost()){
			$ids = $this->request->param();
			$operate_log = '';
			if(count($ids)<1){
				$this->error('请选择要禁用的教师后台账号！');
			}
			else{
				for($i=0;$i<count($ids['ids']);$i++){
					$is_exist_teacher[$i] = db('teacher')->where('id='.$ids['ids'][$i])->find();
					if(!$is_exist_teacher[$i]){
						//反馈
						$operate_log = $operate_log . 'ID：'.$ids['ids'][$i].'的教师不存在！</br>';
					}
					else{
						$is_exist_admin[$i] = db('user')->where('id='.$is_exist_teacher[$i]['union_id'])->find();
						if(!$is_exist_admin[$i]){
							//禁用反馈
							$operate_log = $operate_log . 'union_id：'.$is_exist_teacher[$i]['union_id'].'的教师后台账号不存在！</br>';
						}
						else{
							//填写日志
							$action = '禁用教师管理员账号'.$is_exist_admin[$i]['user_login'].'union_id为：'.$is_exist_teacher[$i]['union_id'];
							$temp_param = $is_exist_admin[$i];
							unset($temp_param['user_login']);
							unset($temp_param['user_pass']);
							$json_data = json_encode($temp_param);
							$result = '成功';
							$first = self::data_log($action,$json_data,$result);
							if(!$first){$this->error('记录日志错误！ -410');}
							//填写user表user_status为0（禁用）
							$second['user_status'] = '0'; 
							$third = db('user')->where('id='.$is_exist_teacher[$i]['union_id'])->update($second);
							//删除反馈
							if($first && $third){
								$operate_log = $operate_log . 'union_id：'.$is_exist_teacher[$i]['union_id'].'的教师后台账号禁用成功！</br>';
							}
							else{
								$operate_log = $operate_log . 'union_id：'.$is_exist_teacher[$i]['union_id'].'的教师后台账号已经禁用！</br>';
							}
						}
					}
				}
				$this->success($operate_log,url('admin/teacher/find_teacher',array('name'=>$ids['name'],'phone'=>$ids['phone'],'from'=>'ban_teacher')));
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function delete_teacher(){
		if ($this->request->isPost()){
			$ids = $this->request->param();
			$operate_log = '';
			if(count($ids)<1){
				$this->error('请选择要删除的教师！');
			}
			else{
				for($i=0;$i<count($ids['ids']);$i++){
					// 管理员账号是否存在
					$is_exist_teacher[$i] = db('teacher')->where('id='.$ids['ids'][$i])->find();
					
					//删除teacher表数据操作
					if(!$is_exist_teacher[$i]){
						//删除反馈
						$operate_log = $operate_log . 'ID：'.$ids['ids'][$i].'的教师不存在！</br>';
					}
					else{
						$is_exist_admin[$i] = db('user')->where('id='.$is_exist_teacher[$i]['union_id'])->find();
						if(!$is_exist_admin[$i]){
							//删除反馈
							$operate_log = $operate_log . 'union_id：'.$is_exist_teacher[$i]['union_id'].'的教师后台账号不存在！</br>';
						}
						else{
							//删除操作
							//填写日志
							$action = '禁用教师后台账号'.$is_exist_admin[$i]['user_login'].'union_id为：'.$is_exist_teacher[$i]['union_id'];
							$temp_param = $is_exist_admin[$i];
							unset($temp_param['user_login']);
							unset($temp_param['user_pass']);
							$json_data = json_encode($temp_param);
							$result = '成功';
							$first = self::data_log($action,$json_data,$result);
							if(!$first){$this->error('记录日志错误！ -403');}
							//填写user表user_status为0（禁用）
							$second['user_status'] = '0'; 
							$third = db('user')->where('id='.$is_exist_teacher[$i]['union_id'])->update($second);
							//删除反馈
							if($first && $third){
								$operate_log = $operate_log . 'union_id：'.$is_exist_teacher[$i]['union_id'].'的教师后台账号设置为禁用成功！</br>';
							}
							else{
								$operate_log = $operate_log . 'union_id：'.$is_exist_teacher[$i]['union_id'].'的教师后台账号已经禁用！</br>';
							}
						}
						//删除操作
						//填写日志
						$action = '删除教师'.$is_exist_teacher[$i]['name'].'ID为：'.$is_exist_teacher[$i]['id'];
						$temp_param = $is_exist_teacher[$i];
						unset($temp_param['introduction']);
						unset($temp_param['note']);
						$json_data = json_encode($temp_param);
						$result = '成功';
						$first = self::data_log($action,$json_data,$result);
						if(!$first){$this->error('记录日志错误！ -406');}
						//放入回收站
						$second = self::data_recycle('teacher',json_encode($is_exist_teacher[$i]));
						if(!$second){$this->error('数据回收错误！ -407');}
						//删除teacher表中数据
						$third = db('teacher')->where('id='.$ids['ids'][$i])->delete();
						//删除反馈
						if($first && $second && $third){
							$operate_log = $operate_log . 'ID：'.$is_exist_teacher[$i]['id'].',姓名：'.$is_exist_teacher[$i]['name'].'删除成功！</br>';
						}
						else{
							$this->error('未知错误！ -408');
						}
					}
				}
				$this->success($operate_log,url('teacher/index'));
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
}